package com.gopay.scheduler.job;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.CpsGenPayOrder;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.matcher.BankCodeQueryRemoteService;
import com.gopay.remote.matcher.vo.GopayBankInfoVO;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.dao.CpsGenPayOrderDAO;

/**
 * 国付宝自建银行code赋值给付款子订单
 * 
 * @GopayBankCodeAssignToPayOrderJob.java
 * @author fanghw
 * @2016年9月9日 上午11:35:51  www.gopay.com.cn Inc.All rights reserved.
 */
public class GopayBankCodeAssignToPayOrderJob extends GopayBaseJob {
    private Logger logger = LoggerFactory.getLogger(GopayBankCodeAssignToPayOrderJob.class);
    
    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;
    
    @Resource(name = "cpsGenPayOrderDAO")
    private CpsGenPayOrderDAO cpsGenPayOrderDAO;
    
    @Resource(name = "bankCodeQueryClient")
    private BankCodeQueryRemoteService bankCodeQueryClient;
    
    @Override
    protected void doJobInternal() { 
        
        // 当前时间
        Date curDate = new Date();
        // 计算起始日期 最近14天,【因为只处理自动结算标识为0的，故要支持国庆长假后自动结算被转线下情况，天数要>7+3】
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curDate);
        calendar.add(Calendar.DAY_OF_MONTH, -14);
        String startDay = DateUtils.format(calendar.getTime(), "yyyyMMddHHmm");
        
        logger.info("startDay="+startDay);
        
        List<Map<String,String>> orderList=queryOrders(startDay);
        
        logger.info("查询结果数为"+orderList.size());
        
        Map<String,String> r;
        GopayBankInfoVO bankInfoResult=null;
        CpsGenPayOrder po;
        for(int i=0;i<orderList.size();i++){
            r=orderList.get(i);
            try{
                //查询自建银行代码
                bankInfoResult=bankCodeQueryClient.getBankInfoByName(r.get("recvBankName"));
                
                String recvGopayBankCode=null;
                if(bankInfoResult!=null&&StringUtils.isNotBlank(bankInfoResult.getCode())){
                	recvGopayBankCode=bankInfoResult.getCode();
                    
                    
                }else{
                	recvGopayBankCode="other";
                	
                    logger.info("查询自建银行代码失败,订单号为"+r.get("gopayOrderId"));
                }
                
                if(StringUtils.isNotBlank(recvGopayBankCode)){
                	//获取订单
                    po=cpsGenPayOrderDAO.find(CpsGenPayOrder.class,r.get("gopayOrderId"));
                    
                	po.setRecvGopayBankCode(recvGopayBankCode);
                    
                    //保存自建银行代码
                    cpsGenPayOrderDAO.update(po);
                    
                    logger.info("订单号"+r.get("gopayOrderId")+"保存成功,code="+recvGopayBankCode+",rawName="+r.get("recvBankName"));
                }
                
                
            }catch(Exception e){
                logger.error("异常订单号为"+r.get("gopayOrderId"),e);
            }
        }
        
    }
    
    private List<Map<String,String>>  queryOrders(String startDay){
        List<Map<String,String>> orderList=new ArrayList<Map<String,String>>();
        
        //sql
        StringBuilder sb = new StringBuilder();        
        sb.append("  select t.gopay_order_id, ");
        sb.append("  t.recv_bank_name ");
        sb.append("  from cps_gen_pay_order t ");
        sb.append(" where 1 = 1 ");
        sb.append("  and t.auto_settle ='0' ");
        sb.append("  and t.recv_bank_name is not null ");
        sb.append("  and t.recv_gopay_bank_code is null ");
        sb.append("  and t.created_ts > to_date(:startDay, 'yyyymmddhh24mi') ");

        
        //map
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startDay",startDay);
        
        //查询
        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        Map<String,String> r;  
        if (rsList != null && rsList.size() > 0) {
            for (Object[] arr : rsList) {
                r=new HashMap<String,String>();
                r.put("gopayOrderId", (String)arr[0]);
                r.put("recvBankName", (String)arr[1]);
                
                orderList.add(r);
            }
        }
        
        return orderList;
    }

}
